<template>
  <div class="consult">
    <el-row>
      <el-col :span="6">
        <div style="height: 300px">
          <div style="height: 50px; margin: 10px">
            <el-radio-group
              size="medium"
              v-model="activeName"
              style="margin-bottom: 30px"
              @change="handleClickTabs"
            >
              <el-radio-button label="A">机构类</el-radio-button>
              <el-radio-button label="B">人员类</el-radio-button>
              <el-radio-button label="C">班子类</el-radio-button>
            </el-radio-group>
            <el-button
              style="float: right"
              size="medium"
              type="primary"
              plain
              @click="addTagGroup(1)"
              >新增</el-button
            >
          </div>
          <!-- 机构类+人员类+班子类 -->
          <div class="organization">
            <el-tree
              ref="tree"
              :data="tagGroups"
              @node-click="handleNodeClick"
              :current-node-key="currentNode"
              highlight-current
              :default-expanded-keys="treeExpandOpenKeys"
              @node-expand="handleNodeTreeExpand"
              @node-collapse="handleNodeTreeCollapse"
              :props="defaultProps"
              node-key="id"
              :expand-on-click-node="true"
              :render-content="renderContent"
            >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span style="display: inline-block">{{ node.label }}</span>
                <span style="display: inline-block; margin-right: 30px">
                  <el-button
                    type="primary"
                    plain
                    size="mini"
                    @click.stop="() => appendGroup(2, data)"
                  >
                    <i class="el-icon-plus"></i>
                  </el-button>
                  <el-button
                    size="mini"
                    type="danger"
                    plain
                    @click.stop="groupDel(data, 2)"
                  >
                    <i class="el-icon-delete"></i>
                  </el-button>
                </span>
              </span>
            </el-tree>
          </div>
        </div>
      </el-col>
      <!-- 机构类+人员类+班子类 -->
      <el-col
        :span="18"
        class="organizationTable"
        style="overflow-y: scroll"
        :style="{ height: heightCard }"
      >
        <el-card class="box-card" style="height: 440px">
          <div
            style="
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin: 20px 20px 10px 20px;
            "
          >
            <h4>标签定义:</h4>
            <div>
              <el-button
                type="primary"
                size="medium"
                plain
                @click="addTagGroup(3)"
                >新增</el-button
              >
            </div>
          </div>
          <div style="padding: 0 20px 0 20px">
            <vxe-table
              border
              ref="xTable"
              :resizable="true"
              :align="allAlign"
              :data="tags"
              :height="heightTableTag"
              :scroll-y="{ enabled: false }"
              highlight-current-row
              @current-change="handleTagClick"
            >
              <vxe-column title="序号" type="seq" width="80"></vxe-column>
              <vxe-column
                title="定义名"
                field="tagName"
                width="350"
              ></vxe-column>
              <vxe-column
                title="code值"
                field="tagCode"
                width="200"
              ></vxe-column>
              <vxe-column title="排序" field="tagSort" width="150"></vxe-column>
              <vxe-column title="标记类型" width="200">
                <template slot-scope="scope">
                  <span v-if="scope.row.tagAutoFlag === '1'">自动标签标记</span>
                  <span v-else-if="scope.row.tagAutoFlag === '2'"
                    >手动标签标记</span
                  >
                </template>
              </vxe-column>
              <vxe-column title="状态" width="200">
                <template slot-scope="scope">
                  <el-switch
                    class="switchStyle"
                    v-model="scope.row.tagStatue"
                    active-value="0"
                    inactive-value="2"
                    active-text="ON"
                    inactive-text="OFF"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    disabled
                  >
                  </el-switch>
                </template>
              </vxe-column>
              <vxe-column title="操作" width="200">
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    size="medium"
                    plain
                    @click="groupUpdate(3, scope.row)"
                    >修改</el-button
                  >
                  <el-button
                    type="danger"
                    size="medium"
                    plain
                    @click="tagRequirementDelete(scope.row)"
                    >删除</el-button
                  >
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </el-card>
        <el-card class="box-card" style="overflow-y: scroll">
          <div style="padding: 10px">
            查询条件运算方式：<el-input
              size="medium"
              v-model="searchOperate"
              style="width: 500px"
              @change="inputValue"
            />
            <el-button
              type="primary"
              size="medium"
              style="float: right; margin-left: 5px"
              @click="onSubmitInput"
              :disabled="isButtonDisabled"
              >条件定义保存</el-button
            >
            <el-button
              type="primary"
              size="medium"
              plain
              style="float: right; margin-left: 5px"
              @click="handleClickTableAdd()"
              >新增</el-button
            >
            <el-button
              type="danger"
              style="float: right; margin-left: 5px"
              size="medium"
              plain
              @click="tableDel"
              >删除</el-button
            >
          </div>
          <p style="color: red; margin-left: 110px">
            编写条件定义的运算逻辑。如:同时满足条件1和2，然后在满足条件3，输入框填写<br />(1+2)+3。同表之间使用括号包裹
          </p>
          <div
            style="
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin: 10px 20px 0 20px;
            "
          >
            <h4>条件定义:</h4>
            <span style="color: red">多个比较值使用|分割</span>
          </div>
          <div style="padding: 0 20px 0 20px">
            <vxe-table
              border
              ref="xTable"
              :resizable="true"
              :align="allAlign"
              :data="tableData"
              :height="heightTable"
              :scroll-y="{ enabled: false }"
              highlight-current-row
              @current-change="handleCurrentRow"
            >
              <vxe-column width="60" align="center">
                <template #default>
                  <span class="drag-btn">
                    <i class="vxe-icon--menu"></i>
                  </span>
                </template>
              </vxe-column>
              <vxe-column title="序号" type="seq" width="60"></vxe-column>
              <vxe-column title="表名" field="tabName" width="300">
                <template slot-scope="scope">
                  <el-select
                    ref="produceRef"
                    v-model="scope.row.tabName"
                    placeholder="请选择"
                    clearable
                    @change="tableNameChang($event, scope.row)"
                  >
                    <el-option
                      v-for="item in nameOption"
                      :key="item.tableName"
                      :label="item.tableShowName"
                      :value="item.tableName"
                    >
                    </el-option>
                  </el-select>
                </template>
              </vxe-column>
              <vxe-column title="字段" field="tagField" width="300">
                <template slot-scope="scope">
                  <tagOperatorField
                    v-model="scope.row.tagField"
                    :row="scope.row"
                    @change="handleTagOperator($event, scope.row)"
                  />
                </template>
              </vxe-column>
              <vxe-column title="比较符" field="tagOperator" width="300">
                <template slot-scope="scope">
                  <el-select
                    @change="$forceUpdate()"
                    v-model="scope.row.tagOperator"
                    placeholder="请选择"
                    clearable
                  >
                    <el-option
                      v-for="item in comparisonOptions"
                      :key="item.CODE"
                      :label="item.NAME"
                      :value="item.CODE"
                    >
                    </el-option>
                  </el-select>
                </template>
              </vxe-column>
              <vxe-column field="tagCondition" title="比较值" width="350">
                <template slot-scope="scope">
                  <custum-type
                    v-model="scope.row.tagCondition"
                    :row="scope.row"
                    @change="handleConditionChange($event, scope.row)"
                  />
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <tagAddDialog
      ref="tagAddDialogRefs"
      v-if="tagAddDialogFlag"
      @initData="getConsultList"
      @getTagList="getTagList"
      @on-group-add-success="handleGroupAddSuccess"
    />
    <tagUpdateDialogFrist
      ref="tagUpdateDialogFristRefs"
      v-if="tagUpdateDialogFristFlag"
      @getTagList="getTagList"
    />
    <tagButtonClickEvent
      ref="tagButtonClickEventRefs"
      :list="tableData"
      @addData="handleClickTableAdd"
      v-if="tagButtonClickEventFlag"
    />
    <appendGroupAdd
      v-if="appendGroupAddFlag"
      ref="appendGroupAddRefs"
      @initData="getConsultList"
      @addData="appendGroup"
      @on-group-add-success="handleGroupAddSuccess"
    />
  </div>
</template>
  
<script>
import tagAddDialog from "./componentsConsult/tagAddDialogFrist.vue";
import tagUpdateDialogFrist from "./componentsConsult/tagUpdateDialogFrist";
import tagButtonClickEvent from "./componentsConsult/tagButtonClickEvent.vue";
import CustumType from "./componentsConsult/custumType.vue";
import tagOperatorField from "./componentsConsult/tagOperatorField.vue";
import appendGroupAdd from "./componentsConsult/appendGroupAdd";
import Sortable from "sortablejs";
import {
  consultList,
  tagDefineDelete,
  queryDict,
  tagTableAndColumnConfigList,
  tagRequirementList,
  saveTagRequirementEdit,
  tagRequirementDelete,
} from "@/api/students/organization/consult";
import store from "@/store";
export default {
  components: {
    tagAddDialog,
    tagUpdateDialogFrist,
    tagButtonClickEvent,
    CustumType,
    tagOperatorField,
    appendGroupAdd,
  },
  data() {
    return {
      activeName: "A",
      heightCard: window.innerHeight - 132 + "px",
      heightTable: window.innerHeight - 500 + "px",
      heightTableTag: window.innerHeight - 600 + "px",
      tagGroups: [],
      categories: [],
      tags: [],
      categoriesList: null,
      groupData: null,
      tagsRow: null,
      allAlign: "center",
      tableData: [],
      nameOption: [],
      fieldOptions: [],
      comparisonOptions: [],
      selectedGroupIndex: 0,
      selectedCategoryIndex: 0,
      selectTagsIndex: 0,
      tagAddDialogFlag: false,
      tagUpdateDialogFristFlag: false,
      tagButtonClickEventFlag: false,
      currentRow: null,
      searchOperate: "",
      inputId: "",
      inputTagDefineId: "",
      inputTagFormula: "",
      tagsClickList: null,
      fieldValues: "",
      typeTagCondition: "",
      tagConditionOption: [], //比较符数组
      isButtonDisabled: false, // 按钮是否被禁用
      timer: null, // 定时器变量
      searchOperateValue: "",
      tagSorts: "",
      tableDataList: [],
      defaultProps: {
        children: "children",
        label: "tagName",
      },
      tabName: "A",
      dialogVisible: false,
      labelPosition: "right",
      appendGroupAddFlag: false,
      currentPage: 1,
      totalItems: 0,
      perPage: 9999999,
      nodeData: null,
      treeExpandOpenKeys: [],
      currentNode: null,
    };
  },
  computed: {
    currentGroup() {
      return this.tagGroups[this.selectedGroupIndex];
    },
    currentCategory() {
      return this.currentGroup.categories[this.selectedCategoryIndex]; // 默认显示第一个分类
    },
  },
  created() {
    this.rowDrop();
    this.getConsultList();
    this.queryDict();
    this.tableNameList();
  },
  beforeDestroy() {
    if (this.sortable) {
      this.sortable.destroy();
    }
  },
  methods: {
    renderContent(h, { node, data }) {
      return (
        <span>
          <i class="el-icon-folder-opened" style="margin-right: 8px;color: rgb(246, 189, 49);"></i> {node.label}
        </span>
      );
    },
    handleClickTabs(type) {
      this.tabName = type;
      this.tags = [];
      this.searchOperate = "";
      this.tableData = [];
      this.getConsultList();
      this.tableNameList();
      this.nodeData = "";
      this.currentRow = "";
    },
    // 新增树子节点
    appendGroup(type, data) {
      this.appendGroupAddFlag = true;
      this.$nextTick(() => {
        this.$refs.appendGroupAddRefs.init(type, data, this.tabName);
      });
    },
    tableNameChang(value, row) {
      this.$set(row, "tabName", value);
      this.$set(row, "tagField", "");
      this.$set(row, "tagCondition", "");
    },
    // 表名
    tableNameList() {
      const params = {
        userId: store.getters.user_id.toString(),
        userName: store.getters.userName.toString(),
        token: store.getters.token.toString(),
        orgOrPer: this.tabName, //切换机构人员班子时传值
        type: "1",
      };
      tagTableAndColumnConfigList(params).then((res) => {
        this.nameOption = res.resultdata;
      });
    },
    // 比较符
    queryDict() {
      const params = {
        userId: store.getters.user_id.toString(),
        userName: store.getters.userName.toString(),
        token: store.getters.token.toString(),
      };
      queryDict(params).then((res) => {
        this.comparisonOptions = res.resultdata;
      });
    },
    // 默认展示的分类的数据
    getConsultList() {
      const params = {
        userId: store.getters.user_id.toString(),
        userName: store.getters.userName.toString(),
        token: store.getters.token.toString(),
        parentId: this.tabName,
        tagGroupId: this.tabName,
        tagType: "2",
      };
      consultList(params).then((result) => {
        // 可能会出错 ,因为你接口获取的数据 没有 resultdata.data
        if (!Array.isArray(result.resultdata.data)) return;

        this.tagGroups = result.resultdata.data;
        const [treeItem] = this.tagGroups;
        this.$nextTick(() => {
              // todo 在这里设置
              this.$refs.tree.setCurrentKey(this.tagGroups[0].id)
            })

        if (treeItem) {
          this.handleNodeClick(treeItem);
        }
      });
    },
    // 标签分组的数据
    handleGroupClick(groupData, index) {
      this.groupData = groupData;
      const params = {
        userId: store.getters.user_id.toString(),
        userName: store.getters.userName.toString(),
        token: store.getters.token.toString(),
        parentId: this.groupData.id,
        tagGroupId: this.tabName,
        tagType: "2",
      };
      consultList(params).then((result) => {
        // 分类
        this.categories = result.resultdata.data;
        if (this.categories.length > 0) {
          this.handleCategoryClick(this.categories[0], 0); // 获取第一个标签分类数据并展示第一个标签定义数据
        } else {
          // 清空标签分类和标签定义数据
          this.categories = [];
          this.tags = [];
        }
      });
      this.selectedGroupIndex = index;
      this.selectedCategoryIndex = 0; // 将标签分类下标设置为0
      this.selectTagsIndex = 0; // 将标签定义下标设置为0
    },
    // 条件定义的新增
    handleClickTableAdd(newData = { id: "" }) {
      if (this.tagsClickList == null || this.tagsClickList == "") {
        this.$message({
          message: "请选择标签定义的任意一条数据",
          type: "warning",
        });
        return;
      }
      this.tagButtonClickEventFlag = true;
      this.$nextTick(() => {
        this.$refs.tagButtonClickEventRefs.init();
      });
      newData.tagSort = this.tableData.length;
      this.tableData.push(newData);
      this.tableDataList = this.tableData;
      console.log(this.tableData, "tabledata");
    },
    handleCurrentRow(currentRow) {
      this.currentRow = currentRow.row;
    },
    handleNodeClick(data) {
      this.currentNode = data.id;
      this.nodeData = data;
      this.currentRow = "";
      this.tagsClickList = "";
      this.handleCategoryClick(data);
      this.tableData = [];
      this.searchOperate = "";
    },

    //定义的数据
    handleCategoryClick(data, categoryIndex) {
      this.currentRow = "";
      this.tagsClickList = "";
      // 点击的是父节点，不执行任何操作
      this.categoriesList = data;
      const params = {
        userId: store.getters.user_id.toString(),
        userName: store.getters.userName.toString(),
        token: store.getters.token.toString(),
        parentId: this.categoriesList.id,
        rows: this.perPage,
        page: this.currentPage,
        tagGroupId: this.tabName,
        tagType: "3",
      };
      consultList(params).then((result) => {
        // 定义
        this.tags = result.resultdata.data;
        this.totalItems = result.resultdata.count;
      });
      this.selectedCategoryIndex = categoryIndex;
    },
    // 点击标签定义
    handleTagClick(currentRow) {
      this.tagsClickList = null;
      this.tagsClickList = currentRow.row;
      this.tableData = [];
      this.searchOperate = "";
      this.getTableList();
    },
    getTagList() {
      const params = {
        userId: store.getters.user_id.toString(),
        userName: store.getters.userName.toString(),
        token: store.getters.token.toString(),
        parentId: this.categoriesList.id,
        rows: this.perPage,
        page: this.currentPage,
        tagGroupId: this.tabName,
        tagType: "3",
      };
      consultList(params).then((result) => {
        // 定义
        this.tags = result.resultdata.data;
        this.totalItems = result.resultdata.count;
      });
    },
    // 新增
    addTagGroup(type) {
      if (type === 3) {
        if (this.nodeData == null || this.nodeData == "") {
          this.$message({
            message: "请先选择标签分组后新增",
            type: "warning",
          });
          return;
        }
      }
      this.tagAddDialogFlag = true;
      this.$nextTick(() => {
        this.$refs.tagAddDialogRefs.init(
          type,
          this.groupData,
          this.categoriesList,
          this.tabName
        );
      });
    },
    // 修改
    groupUpdate(type, data) {
      this.tagUpdateDialogFristFlag = true;
      this.$nextTick(() => {
        this.$refs.tagUpdateDialogFristRefs.init(
          type,
          data,
          this.groupData,
          this.categoriesList,
          this.tabName
        );
      });
    },
    // 获取表格数据
    getTableList() {
      const params = {
        userId: store.getters.user_id.toString(),
        userName: store.getters.userName.toString(),
        token: store.getters.token.toString(),
        tagDefineId: this.tagsClickList.id,
        tagFormula: this.searchOperate,
      };
      tagRequirementList(params).then((result) => {
        this.look_tableData_res = true
        this.tableData = result.resultdata.data; //表格
        
        if (result.resultdata.tagOperation) {
          this.inputId = result.resultdata.tagOperation.id || "";
          this.searchOperate = result.resultdata.tagOperation.tagFormula || "";
        } else {
          this.inputId = "";
          this.searchOperate = "";
        }
      });
    },
    inputValue() {
      if (this.searchOperate == null || this.searchOperate.trim() == "") {
        this.$message.warning("运算公式不可为空！");
        this.isButtonDisabled = true; // 输入为空时禁用保存按钮
      } else {
        this.isButtonDisabled = false; //合法时解除禁用
      }
      //验证公式合法性
      if (this.formulaJudge(this.searchOperate)) {
        let rowIndex = this.searchOperate.replace(/[^0-9]/gi, "");
        let points = rowIndex.split("");
        points.sort(function (a, b) {
          return b - a;
        });
        if (points[0] > this.tableData.length) {
          this.$message.warning(
            "运算公式中的最大值超过条件个数，请检查后重试！"
          );
          this.isButtonDisabled = true; // 公式不合法时禁用保存按钮
        } else {
          this.isButtonDisabled = false; //合法时解除禁用
        }
        this.tableDataList;
        // this.onSubmitInput();
      } else {
        this.$message.warning("运算公式不合法，请检查后重试！");
        this.isButtonDisabled = true; // 公式不合法时禁用保存按钮
      }
    },

    // 删除
    groupDel(group, type) {
      this.$confirm("确定删除当前行?", "操作提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        const params = {
          userId: store.getters.user_id.toString(),
          userName: store.getters.userName.toString(),
          token: store.getters.token.toString(),
          id: group.id,
          type: type,
        };
        tagDefineDelete(params).then((response) => {
          if (response.resultdata) {
            this.$message({
              type: "success",
              message: response.resultdata,
            });
            this.getConsultList();
          } else {
            this.$message({
              type: "error",
              message: response.resultdata,
            });
          }
        });
      });
    },
    // 表格删除
    tableDel() {
      if (this.currentRow == null || this.currentRow == "") {
        this.$message({
          type: "warning",
          message: "请选中一条数据进行删除",
        });
        return;
      }
      this.$confirm("确定删除当前行?", "操作提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        const params = {
          userId: store.getters.user_id.toString(),
          userName: store.getters.userName.toString(),
          token: store.getters.token.toString(),
          id: this.currentRow.id,
        };
        tagRequirementDelete(params).then((response) => {
          if (response.result) {
            this.$message({
              type: "success",
              message: response.resultdata,
            });
            this.getTableList();
            console.log(this.currentRow,"this.currentRow")
            this.currentRow = null;
          } else {
            this.$message({
              type: "error",
              message: response.resultdata,
            });
          }
        });
      });
    },
    // 运算方式的删除
    tagRequirementDelete(tag) {
      this.$confirm("确定删除当前行?", "操作提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        const params = {
          userId: store.getters.user_id.toString(),
          userName: store.getters.userName.toString(),
          token: store.getters.token.toString(),
          id: tag.id,
          tagDefineId: tag.id,
          tagStatue: tag.tagStatue,
          all: "1",
          type: "3",
        };
        tagRequirementDelete(params).then((response) => {
          if (response.result == true) {
            this.$message({
              type: "success",
              message: response.resultdata,
            });
            this.getTagList();
          } else {
            this.$message({
              type: "error",
              message: response.resultdata,
            });
          }
        });
      });
    },
    // 字段
    handleTagOperator(e, row) {
      const { val, item, type } = e;
      this.$set(row, "tagField", val);
      this.$set(row, "tfieldType", item.fieldType);
      row["tdictCode"] = item.dictCode;
      this.$set(row, "tdictCode", item.dictCode);
      
      if(type == 1) {

      } else {
        this.$set(row, "tagCondition", "");
      }

    },
    // 比较值
    handleConditionChange(e, row) {
      this.$set(row, "tagCondition", e);
    },
    //验证公式合法性
    formulaJudge(string) {
      //去除左边及右边的括号（这个是我的公式里面有特殊字符）
      let str = string.replace("{", "").replace("}", "");
      // 剔除空白符
      string = str.replace(/\s/g, "");
      // 错误情况，空字符串
      if ("" === string) {
        return false;
      }
      // 检查数字是否重复出现
      if (/(\d).*\1/.test(string)) {
        return false;
      }
      // 包含非法字符（只允许数字、+、-、(、)，括号为英文括号）
      if (!/^[\d\+\-\(\)]+$/.test(string)) {
        return false;
      }
      // 错误情况，运算符连续
      if (/[\+\-\*\/]{2,}/.test(string)) {
        return false;
      }
      // 空括号
      if (/\(\)/.test(string)) {
        return false;
      }
      // 最后一个符号是加、减、乘、除符号
      if (/[\+\-\*\/]$/.test(string)) {
        return false;
      }
      // 错误情况，括号不配对
      let stack = [];
      for (let i = 0, item; i < string.length; i++) {
        item = string.charAt(i);
        if ("(" === item) {
          stack.push("(");
        } else if (")" === item) {
          if (stack.length > 0) {
            stack.pop();
          } else {
            return false;
          }
        }
      }
      if (0 !== stack.length) {
        return false;
      }
      // 错误情况，(后面是运算符
      if (/\([\+\-\*\/]/.test(string)) {
        return false;
      }
      // 错误情况，)前面是运算符
      if (/[\+\-\*\/]\)/.test(string)) {
        return false;
      }
      // 错误情况，(前面不是运算符
      if (/[^\+\-\*\/\(]\(/.test(string)) {
        return false;
      }
      // 错误情况，)后面不是运算符
      if (/\)[^\+\-\*\/\)]/.test(string)) {
        return false;
      }
      // **错误情况最后一个字符是**+-*/
      if (/\*[\+\-\*\/]$/.test(string)) {
        return false;
      }
      return true;
    },

    rowDrop() {
      this.$nextTick(() => {
        let xTable = this.$refs.xTable;
        this.sortable = Sortable.create(
          xTable.$el.querySelector(".body--wrapper>.vxe-table--body tbody"),
          {
            handle: ".vxe-body--row",
            animation: 150,
            onEnd: ({ newIndex, oldIndex }) => {
              // 解决方案
              this.tableData.splice(
                newIndex,
                0,
                this.tableData.splice(oldIndex, 1)[0]
              );
              // 更新tagSort值
              this.tableData.forEach((item, index) => {
                item.tagSort = index;
              });
              var newArray = this.tableData.slice(0);
              this.tableData = [];
              this.$nextTick(function () {
                this.tableData = newArray;
              });
            },
          }
        );
      });
    },
    // input框的保存和修改
    onSubmitInput() {
      for (const item of this.tableData) {
        if (!item.tabName || item.tabName === "") {
          // 判断表名是否已选择
          this.$message.warning("请确保新增数据已选择表名！");
          return;
        }
        if (!item.tagField || item.tagField === "") {
          // 判断字段是否已选择
          this.$message.warning("请确保新增数据已选择字段！");
          return;
        }
        if (!item.tagOperator || item.tagOperator === "") {
          // 判断比较符是否已选择
          this.$message.warning("请确保新增数据已选择比较符！");
          return;
        }
        if (!item.tagCondition || item.tagCondition === "") {
          // 判断比较值是否已填写
          this.$message.warning("请确保新增数据已填写比较值！");
          return;
        }
      }
      if (this.searchOperate == null || this.searchOperate.trim() == "") {
        this.$message.warning("运算公式不可为空！");
        this.isButtonDisabled = true;
        return;
      } else if (this.formulaJudge(this.searchOperate)) {
        let rowIndex = this.searchOperate.replace(/[^0-9]/gi, "");
        let points = rowIndex.split("");
        points.sort(function (a, b) {
          return b - a;
        });
        if (points[0] > this.tableData.length) {
          this.$message.warning(
            "运算公式中的最大值超过条件个数，请检查后重试！"
          );
          this.isButtonDisabled = true; // 公式不合法时禁用保存按钮
          return;
        }
        this.isButtonEnabled = false;
      } else {
        this.$message.warning("运算公式不合法，请检查后重试！");
        this.isButtonDisabled = true; // 公式不合法时禁用保存按钮
        return;
      }
      this.isButtonDisabled = true; //点击时立即禁用按钮
      const params = {
        userId: store.getters.user_id.toString(),
        userName: store.getters.userName.toString(),
        token: store.getters.token.toString(),
        tagDefineId: this.tagsClickList.id,
        list: [],
        tagOperation: {
          id: this.inputId,
          tagFormula: this.searchOperate,
        },
      };
      this.tableData.forEach((item) => {
        const listItem = {
          tagSort: item.tagSort,
          tabName: item.tabName,
          tagField: item.tagField,
          tagOperator: item.tagOperator,
          tagCondition: item.tagCondition,
        };
        params.list.push(listItem); // 将当前行数据添加到list数组中
      });
      saveTagRequirementEdit(params).then((res) => {
        if (res.result) {
          this.$message({
            message: "操作成功",
            type: "success",
          });
          this.getTableList();
        }
        this.timer = setTimeout(() => {
          this.isButtonDisabled = false; // 启用按钮
          clearTimeout(this.timer); // 清除定时器
        }, 2000);
      });
    },
    // 添加成功或者编辑成功，回调方法
    // 这个方法是为之前的结构写的
    handleGroupAddSuccess(e) {
      const { type, data } = e;
      // 这个 type 到时候可以用来干嘛用，现在我不做任何作用先暴露出来
      const list = this.tagGroups;
      if (Array.isArray(list)) {
        let index = list.findIndex((f) => f === data);
        this.handleGroupClick(data, index < 0 ? 0 : index);
      }
    },
    handleNodeTreeExpand(data) {
      if (this.treeExpandOpenKeys.indexOf(data.id) == -1) {
        this.treeExpandOpenKeys.push(data.id);
      }
    },
    handleNodeTreeCollapse(data) {
      this.treeExpandOpenKeys = this.treeExpandOpenKeys.filter(
        (f) => f !== data.id
      );
    },
  },
};
</script>
<style scoped>
.consult {
  width: 100%;
  height: 100%;
  background-color: #ffffff;
}
>>> .el-tree-node__content {
  display: flex;
  align-items: center;
  height: 3.354vw;
  border: 1px solid #eee;
  cursor: pointer;
}
>>> .el-tree {
  height: calc(100vh - 260px);
  overflow-y: scroll;
}
>>> .custom-tree-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
}
/* >>>.el-tree-node:focus > .el-tree-node__content {
  background-color: rgba(135, 206, 235, 0.3);
  color: #409eff;
  font-weight: bold;
} */
/deep/ .el-tree .el-tree-node.is-current > .el-tree-node__content {
  background-color: rgba(135, 206, 235, 0.3);
}
.tagGroup ul {
  list-style: none;
}

.tagGroup ul li {
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.tagGroup ul li span.ellipsis-text {
  display: inline-block;
  width: 80px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.active {
  /* background: #ecf5ff;
  color: #409eff; */
  background: #cfe5fc;
  color: #000;
}
>>> .el-card__header {
  background: linear-gradient(180deg, #fff, #ededed);
}
>>> .el-card__body {
  padding: 0;
  /* height: calc(100vh - 200px); */
  overflow-y: auto;
}
>>> .vxe-table--render-default .vxe-table--body,
.vxe-table--render-default .vxe-table--footer,
.vxe-table--render-default .vxe-table--header {
  width: 100%;
}
.switchStyle /deep/ .el-switch__label {
  position: absolute;
  display: none;
  color: #fff;
}
>>> .el-switch__core {
  background-color: rgba(166, 166, 166, 1);
}
.switchStyle /deep/ .el-switch__label--left {
  z-index: 9;
  left: 20px;
}
.switchStyle /deep/ .el-switch__label--right {
  z-index: 9;
  left: 4px;
}
.switchStyle /deep/ .el-switch__label.is-active {
  display: block;
}
>>> .el-switch__core {
  width: 3.125vw !important;
}
>>> .el-switch.is-checked .el-switch__core {
  width: 3.125vw !important;
}
>>> .el-switch.is-disabled {
  opacity: 1.6;
}
.el-tree .el-icon-caret-right:before {
    content: '\e7a0';
    font-size: 15px;
}
.el-tree .el-tree-node__expand-icon.expanded.el-icon-caret-right:before {
    content: '\e7a2';
    font-size: 15px;
}
</style>